//
//  EmoticonToolBar.swift
//  自定义表情键盘
//
//  Created by YYY on 2017/9/5.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

import UIKit

class EmoticonToolBar: UIView {

    override func awakeFromNib() {
        
        //初始化布局
        setupUI()
    }

    //刷新布局
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let count = subviews.count
        let width = bounds.width/CGFloat(count)
        
        let rect = CGRect(x: 0, y: 0, width: width, height: bounds.height)
        
        for (i, btn) in subviews.enumerated()
        {
            btn.frame = rect.offsetBy(dx: CGFloat(i) * width, dy: 0)
        }
    }
}

private extension EmoticonToolBar
{
    func setupUI()
    {
        //初始化布局
        let manager = EmotionManager.shared
        
        for model in manager.emotionsGroupArray
        {
            //按钮实例化
            let btn = UIButton()
            
            //compose_emotion_table_left_normal@2x
        
            //compose_emotion_table_left_selected@2x
            //设置按钮属性
            let imageNameNormal = "compose_emotion_table_\(model.bgImageName ?? "")_normal"
            let imageNameSelected = "compose_emotion_table_\(model.bgImageName ?? "")_selected"
            
            var imageNormal = UIImage(named: imageNameNormal, in: manager.bundle, compatibleWith: nil)
            var imageSelected = UIImage(named: imageNameSelected, in: manager.bundle, compatibleWith: nil)
            
            //拉伸图片
            let size = imageNormal?.size ?? CGSize()
            let inset = UIEdgeInsetsMake(size.height * 0.5, size.width * 0.5, size.height * 0.5, size.width * 0.5)
            
            imageNormal = imageNormal?.resizableImage(withCapInsets: inset)
            imageSelected = imageSelected?.resizableImage(withCapInsets: inset)
            
            //设置背景图片
            btn.setBackgroundImage(imageNormal, for: .normal)
            btn.setBackgroundImage(imageSelected, for: .selected)
            btn.setBackgroundImage(imageSelected, for: .highlighted)
            
            btn.setTitle(model.groupName, for: .normal)
            btn.setTitleColor(UIColor.white, for: .normal)
            btn.setTitleColor(UIColor.darkGray, for: .highlighted)
            btn.setTitleColor(UIColor.darkGray, for: .selected)
            btn.sizeToFit()
            
            //添加按钮
            addSubview(btn)
        }
        
    }
}
